package com.wang.ssm.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.wang.ssm.pojo.User;
import com.wang.ssm.service.StuService;
import com.wang.ssm.util.Result;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author 王瑞杰
 * date 2023/10/24
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {


    @Resource
    private StuService service;

    @GetMapping("/users")
    public Result findAll(){
        return  new Result<>(200,"查询OK",true,this.service.finduser());
    }
    @GetMapping("/type")
    public Result findType(){
        return  new Result<>(200,"查询Ok",true,this.service.findType());
    }
    @GetMapping("/userid/")
    public Result findById(@RequestParam(name="uid",required = false) String uid){
        return service.findById(uid)!=null
                ? new Result<>(200,"成功",true,service.findById(uid))
                : new Result<>(201,"失败",false);
    }

    @PostMapping("/uppass")
    public Result uppass(@RequestBody User user){
        return service.uppass(user)
                ? new Result<>(200,"修改成功",true)
                : new Result<>(201,"修改失败",false);
    }
    @PostMapping("/save")
    public Result save(User user, @RequestParam MultipartFile head) throws IOException {
        String originalFilename = head.getOriginalFilename();
        String uuid = IdUtil.fastSimpleUUID();
        //路径
        String path = System.getProperty("user.dir")+"/src/main/resources/upload/"+uuid+"_"+originalFilename;
        FileUtil.writeBytes(head.getBytes(),path);
        //图片的处理
        String pic = Base64.encode(head.getBytes());
        System.out.println(pic);
        user.setPhoto(pic);
        return  this.service.saveuser(user)
                ?   new Result<>(200,"保存成功",true)
                :  new Result<>(201,"保存失败",false);
    }
}




//创建一个新的spring项目，把原jack** EE项目你写的类全部复制进去（除了配置文件config和init,因为spring用注解装配）,properties文件你自己加上那四个数据库配置，spring-datasource.*****(username,password,url,driver)依赖加个hutool-all就行，你要写分页还得加个pagehelper,mapper类全部加上@mapper注解,跨域问题在控制器上加@CrossOrigin,基本就可以正常使用了

//补充一点，有时候启动'启动类'会报错说找不到主类，这时候启动test里的测试类再启动'启动类'就可以了